package com.zhai.boot.interceptor;


import com.zhai.boot.annotation.TrimField;
import com.zhai.boot.util.StringUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.regex.Pattern;

/**
 * @author Created by 翟凤玺
 * @package com.zhai.boot.interceptor
 * @project-name zhai-boot
 * @description 去除对象中字符串属性的特殊字符
 * @create-datetime 2019-6-18 10:35
 */
@Aspect
@Configuration
public class TrimInterceptor {

    @Around("execution(public * *(..)) && @annotation(com.zhai.boot.annotation.TrimMethod)")
    public Object interceptor(ProceedingJoinPoint pjp) throws Throwable {
        Object[] args = pjp.getArgs();

        for (int i = 0; i < args.length; ++i) {
            Object clazzObj = args[i];
            ReflectionUtils.doWithFields(clazzObj.getClass(), new ReflectionUtils.FieldCallback() {
                @Override
                public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                    try {
                        TrimField trimField = field.getAnnotation(TrimField.class);
                        if (trimField != null) {
                            PropertyDescriptor pd  = new PropertyDescriptor(field.getName(), clazzObj.getClass());
                            Method method = pd.getReadMethod();
                            Object value = method.invoke(clazzObj,null);
                            if (value instanceof String && StringUtil.isNotBlank(value.toString())){
                                method = pd.getWriteMethod();
                                method.invoke(clazzObj,  Pattern.compile(trimField.regex()).matcher(value.toString()).replaceAll(""));
                            }
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }

            });
        }
        return pjp.proceed();
    }
}